package com.jvtd.demo.amap;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.SystemClock;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationQualityReport;
import com.jvtd.base.JvtdActivity;
import com.jvtd.demo.R;
import com.jvtd.gd_location.JvtdLocation;
import com.jvtd.gd_location.JvtdLocationCallBack;
import com.jvtd.widget.toast.JvtdToast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class GdAlarmLocationActivity extends JvtdActivity implements View.OnClickListener
{
  private static final String ACTION_LOCATION = "ACTION_LOCATION";

  private JvtdToast mToast;
  private Button btnStartLocation;
  private TextView tvResult;
  private EditText etAlarm;
  private PendingIntent alarmPi = null;
  private AlarmManager alarm = null;

  @Override
  protected void bindView()
  {
    TextView tvTitle = findViewById(R.id.tv_title);
    tvTitle.setText("定时唤起CPU");
    Toolbar mToolbar = findViewById(R.id.tool_bar);
    setToolbar(mToolbar, true);

    etAlarm = findViewById(R.id.et_alarm);
    btnStartLocation = findViewById(R.id.bt_location);
    btnStartLocation.setOnClickListener(this);
    tvResult = findViewById(R.id.tv_result);
  }

  @Override
  protected void getLayout()
  {
    setContentView(R.layout.activity_gd_alarm_location);
  }

  @Override
  protected void initViewAndData()
  {
    mToast = new JvtdToast(this, JvtdToast.FLAG_BOTTOM);
    // 创建Intent对象，action为LOCATION
    Intent alarmIntent = new Intent();
    alarmIntent.setAction(ACTION_LOCATION);
    // 定义一个PendingIntent对象，PendingIntent.getBroadcast包含了sendBroadcast的动作。
    // 也就是发送了action 为"LOCATION"的intent
    alarmPi = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
    // AlarmManager对象,注意这里并不是new一个对象，Alarmmanager为系统级服务
    alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
    //动态注册一个广播
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_LOCATION);
    registerReceiver(alarmReceiver, filter);

    JvtdLocation.getInstance(this).setApiKey("707fb1ed21b6b4ba91d71cb818f3b805").init(new JvtdLocationCallBack()
    {
      @Override
      public void onLocationChanged(AMapLocation location)
      {
        StringBuilder sb = new StringBuilder();
        sb.append("定位成功" + "\n");
        sb.append("定位类型: ").append(location.getLocationType()).append("\n");
        sb.append("经    度    : ").append(location.getLongitude()).append("\n");
        sb.append("纬    度    : ").append(location.getLatitude()).append("\n");
        sb.append("精    度    : ").append(location.getAccuracy()).append("米").append("\n");
        sb.append("提供者    : ").append(location.getProvider()).append("\n");

        sb.append("速    度    : ").append(location.getSpeed()).append("米/秒").append("\n");
        sb.append("角    度    : ").append(location.getBearing()).append("\n");
        // 获取当前提供定位服务的卫星个数
        sb.append("星    数    : ").append(location.getSatellites()).append("\n");
        sb.append("国    家    : ").append(location.getCountry()).append("\n");
        sb.append("省            : ").append(location.getProvince()).append("\n");
        sb.append("市            : ").append(location.getCity()).append("\n");
        sb.append("城市编码 : ").append(location.getCityCode()).append("\n");
        sb.append("区            : ").append(location.getDistrict()).append("\n");
        sb.append("区域 码   : ").append(location.getAdCode()).append("\n");
        sb.append("地    址    : ").append(location.getAddress()).append("\n");
        sb.append("地    址    : ").append(location.getDescription()).append("\n");
        sb.append("兴趣点    : ").append(location.getPoiName()).append("\n");
        //定位完成的时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        Date date = new Date(location.getTime());
        String dateStr = df.format(date);
        sb.append("定位时间: ").append(dateStr).append("\n");
        sb.append("***定位质量报告***").append("\n");
        sb.append("* WIFI开关：").append(location.getLocationQualityReport().isWifiAble() ? "开启" : "关闭").append("\n");
        sb.append("* GPS状态：").append(getGPSStatusString(location.getLocationQualityReport().getGPSStatus())).append("\n");
        sb.append("* GPS星数：").append(location.getLocationQualityReport().getGPSSatellites()).append("\n");
        sb.append("****************").append("\n");

        //解析定位结果，
        String result = sb.toString();
        tvResult.setText(result);
      }

      @Override
      public void locationError(int errorCode, String errorInfo)
      {
        //定位失败
        //解析定位结果，
        String result = ("定位失败" + "\n") +
                "错误码:" + errorCode + "\n" +
                "错误信息:" + errorInfo + "\n";
        tvResult.setText(result);
      }

      @Override
      public void onCustomError(String errorInfo)
      {
        mToast.showMessage("errorInfo = " + errorInfo, 500);
      }
    });
  }

  /**
   * 获取GPS状态的字符串
   */
  private String getGPSStatusString(int statusCode)
  {
    String str = "";
    switch (statusCode)
    {
      case AMapLocationQualityReport.GPS_STATUS_OK:
        str = "GPS状态正常";
        break;
      case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
        str = "手机中没有GPS Provider，无法进行GPS定位";
        break;
      case AMapLocationQualityReport.GPS_STATUS_OFF:
        str = "GPS关闭，建议开启GPS，提高定位质量";
        break;
      case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
        str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
        break;
      case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
        str = "没有GPS定位权限，建议开启gps定位权限";
        break;
    }
    return str;
  }

  @Override
  public void onClick(View view)
  {
    if (btnStartLocation.getText().equals("开始定位"))
    {
      setViewEnable(false);
      int alarmInterval = 5;
      String str = etAlarm.getText().toString();
      if (!TextUtils.isEmpty(str))
        alarmInterval = Integer.parseInt(str);
      btnStartLocation.setText("停止定位");
      tvResult.setText("正在定位...");
      startLocation();

      //设置一个闹钟，2秒之后每隔一段时间执行启动一次定位程序
      if (alarm != null)
        alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 2 * 1000, alarmInterval * 1000, alarmPi);
    } else
    {
      setViewEnable(true);
      btnStartLocation.setText("开始定位");
      stopLocation();
      tvResult.setText("定位停止");

      //停止定位的时候取消闹钟
      if (alarm != null)
        alarm.cancel(alarmPi);
    }
  }

  /**
   * 设置控件的可用状态
   */
  private void setViewEnable(boolean isEnable)
  {
    etAlarm.setEnabled(isEnable);
  }

  private void startLocation()
  {
    JvtdLocation.getInstance(this).startLocation();
  }

  private void stopLocation()
  {
    JvtdLocation.getInstance(this).stopLocation();
  }

  @Override
  protected void onDestroy()
  {
    super.onDestroy();
    JvtdLocation.getInstance(this).closeLocationOption();
    JvtdLocation.getInstance(this).stopLocation();
    JvtdLocation.getInstance(this).destoryLocation();

    if (null != alarmReceiver)
    {
      unregisterReceiver(alarmReceiver);
      alarmReceiver = null;
    }
  }

  private BroadcastReceiver alarmReceiver = new BroadcastReceiver()
  {
    @Override
    public void onReceive(Context context, Intent intent)
    {
      if (TextUtils.equals(intent.getAction(), ACTION_LOCATION))
        startLocation();
    }
  };
}
